package top.xchch.tool.resttemplate.client;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import top.xchch.tool.resttemplate.entity.Poetry;

/**
 * @author sai.zhang
 * @date 2021-09-12 11:07
 */
@Slf4j
@RestController
public class PostRequestClient {
    @Autowired
    private RestTemplate restTemplate;

    /**
     * MultiValueMap传参
     */
    @GetMapping("/post01")
    private Poetry post01() {
        MultiValueMap<String, String> requestParam = new LinkedMultiValueMap<>();
        requestParam.add("id", "11");
        requestParam.add("id", "12");
        requestParam.add("author", "xx");

        Poetry poetry = restTemplate.postForObject(
                "http://localhost:8080/find", requestParam, Poetry.class);
        // post01 - postForObject 返回值: {"author":"xx","content":"西塞名山立翠屏，浓岚横入半江青。\n千寻铁锁无由问，石壁空存道者形。\n匹妇顽然莫问因，匹夫何去望千春。\n翻思岵屺传诗什，举世曾无化石人。","id":12,"title":"西塞山二首"}
        log.info("post01 - postForObject 返回值: {}", JSON.toJSONString(poetry));
        return poetry;
    }

    /**
     * body对象传参
     */
    @GetMapping("/post02")
    private Poetry post02() {

        Poetry requestBody = new Poetry();
        requestBody.setId(0L);
        requestBody.setAuthor("xx");
        requestBody.setTitle("西塞山2首");

        HttpHeaders headers = new HttpHeaders();
        HttpEntity<Poetry> httpEntity = new HttpEntity<>(requestBody, headers);
        Poetry poetry = restTemplate.postForObject(
                "http://localhost:8080/find02", httpEntity, Poetry.class);
        // post02 - postForObject 返回值: {"author":"xx","content":"西塞名山立翠屏，浓岚横入半江青。\n千寻铁锁无由问，石壁空存道者形。\n匹妇顽然莫问因，匹夫何去望千春。\n翻思岵屺传诗什，举世曾无化石人。","id":0,"title":"西塞山2首"}
        log.info("post02 - postForObject 返回值: {}", JSON.toJSONString(poetry));
        return poetry;
    }

}
